package me.xiaoyan.ehr.controller;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.xiaoyan.ehr.util.UploadFileUtil;
import me.xiaoyan.ehr.vo.ApiResponseData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author darkingX
 * @since 2021-02-26
 */
@RestController
public class FileUploadController {
    @Value("${application.url}")
    private String applicationUrl;

    /**
     * 文件访问地址
     */
    @Value("${application.upload.url}")
    private String uploadBaseUrl;
    /**
     * 文件保存地址
     */
    @Value("${application.upload.dir}")
    private String uploadDir;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true)
    })
    public ApiResponseData<Map<String, String>> uploadImages(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        ApiResponseData<Map<String, String>> data = new ApiResponseData<>();
        try {
            byte[] bytes = file.getBytes(); // 获取所有文件内容
            // 后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 获取要保存文件的目录
            String realPath = ResourceUtils.getURL(uploadDir).getPath();
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            // 完整的保存路径
            String path = uploadBaseUrl + fileName;
            Map<String, String> uploadFile = new HashMap<>();
            uploadFile.put("url", applicationUrl + path);
            uploadFile.put("path", path);

            // 保存文件
            boolean flag = UploadFileUtil.uploadFile(bytes, realPath, fileName);
            //返回数据
            data.setData(uploadFile);
        } catch (Exception e) {
            e.printStackTrace();
            data.setCode(-1);
            //返回异常
            data.setMessage("上传图片时IO异常:" + e.getMessage());
        }
        return data;
    }


}

